package com.xiaoyu.studyworkspace.task;

import com.xiaoyu.studyworkspace.common.websocketclient.KapaSocketClient;
import com.xiaoyu.studyworkspace.mapper.AutoPlayMapper;
import com.xiaoyu.studyworkspace.mapper.PredictionMapper;
import com.xiaoyu.studyworkspace.pojo.AutoUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

@Component
@Slf4j
public class AutoBettingTask {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private PredictionMapper predictionMapper;

    @Autowired
    private AutoPlayMapper autoPlayMapper;


    /**
     * 3每秒定时任务论询
     *
     * @throws Exception
     */
    @Scheduled(cron = "0/3 * * * * ?")
    public void autoBettingJobHandler() {
        //获取标记
        Optional.ofNullable(redisTemplate.opsForValue().get("new")).ifPresent(flag -> {
            List<AutoUser> autoUsers = autoPlayMapper.selectAllAutoUsers();
            for (AutoUser autoUser : autoUsers) {
                if (autoUser.getIs_auto() == 0) {
                    //取map获取一下，如过存在则停止
                    KapaSocketClient kapaSocketClient = KapaSocketClient.KAPA_SOCKET_CLIENT_MAP.get(autoUser.getUser_id());
                    if (kapaSocketClient != null) {
                        /**
                         * 停止,日志信息记录,写入数据库，停止成功！,修改is_auto
                         */
                        log.info("用户退出:{}", autoUser.getUser_id());
                        autoUser.setIs_auto(0);
                        autoPlayMapper.updateAutoUserIsAuto(autoUser);
                        kapaSocketClient.close();
                        //关闭,且删除该key
                        KapaSocketClient.KAPA_SOCKET_CLIENT_MAP.remove(autoUser.getUser_id());
                    }
                    continue;
                }
                if (autoUser.getIs_auto() == 1) {
                    //从KAPA_SOCKET_CLIENT_MAP取出，是否存在
                    KapaSocketClient kapaSocketClient = KapaSocketClient.KAPA_SOCKET_CLIENT_MAP.get(autoUser.getUser_id());
                    if (kapaSocketClient == null) {
                        //为空则取创建,并且放入map中
                        try {
                            kapaSocketClient = new KapaSocketClient(autoUser, autoPlayMapper, redisTemplate, predictionMapper);
                        } catch (URISyntaxException e) {
                            throw new RuntimeException(e);
                        }
                        KapaSocketClient.KAPA_SOCKET_CLIENT_MAP.put(autoUser.getUser_id(), kapaSocketClient);
                        kapaSocketClient.connect();
                    }
                    if ((int) flag == 1) {
                        //说明已经投入过
                        continue;
                    }
                    kapaSocketClient.setGames((int) flag + 1);
                    kapaSocketClient.setBetted(false);
                }
            }
            if ((int) flag == 1) {
                //说明已经投入过
                return;
            }
            log.info("打印期数上一局期数：{},清空标记", flag);
            //所有用户执行完清空标记,表示当前轮结束
            redisTemplate.opsForValue().set("new", 1);
        });

    }

}
